from datetime import datetime

from django.http import JsonResponse
from django.views import View

from notice.models import Notice, SysNoticeSerializer


# Create your views here.

class OperateNoticeView(View):  # 新增/修改公告数据
    def post(self, request):
        id = request.POST.get("id", None)
        content = request.POST.get("content")
        is_deleted = request.POST.get("is_deleted")
        if id is None :  # 当id为空值时，新增公告数据
            try:
                notice = Notice.objects.create(
                    content=content,
                    publish_time=datetime.now().date(),
                    update_time=datetime.now().date(),
                    is_deleted=is_deleted
                )
                # 查询所有公告数据
                notices = Notice.objects
                return JsonResponse(
                    {"code": 200, "info": "添加成功！", "notices": SysNoticeSerializer(notices, many=True).data})
            except Exception as a:
                return JsonResponse({"code": 500, "info": "添加失败！"})
        else:  # 当id不为空值时，修改公告数据
            try:
                notice = Notice.objects.get(id=id)
                notice.content = content
                notice.update_time = datetime.now().date()
                notice.is_deleted = is_deleted
                notice.save()
                # 查询所有公告数据
                notices = Notice.objects
                return JsonResponse(
                    {"code": 200, "info": "修改成功！", "notices": SysNoticeSerializer(notices, many=True).data})
            except Exception as a:
                return JsonResponse({"code": 500, "info": "修改失败！"})


class SelectNoticeView(View):  # 查询公告数据
    def post(self, request):
        is_deleted = request.POST.get("is_deleted", None)
        try:
            if is_deleted is None or is_deleted == "-1" or is_deleted == "":
                notices = Notice.objects.filter()
                return JsonResponse(
                    {"code": 200, "info": "查询成功！", "notices": SysNoticeSerializer(notices, many=True).data})
            else:
                notices = Notice.objects.filter(is_deleted=is_deleted)
                return JsonResponse(
                    {"code": 200, "info": "查询成功！", "notices": SysNoticeSerializer(notices, many=True).data})
        except Exception as e:
            return JsonResponse({"code": 500, "info": "查询失败！"})
